<template>
    <div>
        <div class="head-project" id="static_position">
            <div class="title"><span>数据库</span></div>
            <Dropdown @on-click="dbEdit">
                <a href="javascript:void(0)">
                    <Icon type="md-menu" size="18"/>
                </a>
                <DropdownMenu slot="list" style="width: 120px">
                    <DropdownItem name="add">新增</DropdownItem>
                </DropdownMenu>
            </Dropdown>
        </div>
        <div v-for="(dbInfo, index) in app.appDbList" :key="index">
            <Form :ref="'formValidate'" :model="dbInfo" v-if="dbInfo" :rules="dbValidate" label-position="top" @submit.native.prevent style="width: 800px; margin-right: 32px">
                <Row :gutter="16">
                    <Col span="12">
                        <FormItem label="数据库" class="item-inline" prop="dbUrl">
                            <Select v-model="dbInfo.dbType" style="width: 120px">
                                <Option value="mysql">mysql</Option>
                                <Option value="oracle">oracle</Option>
                            </Select>
                            <Input v-model="dbInfo.dbUrl" class="item-line-middle"
                                   placeholder="0.0.0.0/localhost"></Input>
                            <Input v-model="dbInfo.dbPort" style="width: 120px" class="item-line-right"
                                   placeholder="port"></Input>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="数据库名称" prop="name">
                            <Input v-model="dbInfo.name" placeholder="数据库名"></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="16">
                    <Col span="12">
                        <FormItem label="数据库用户" prop="dbUser">
                            <Input v-model="dbInfo.dbUser" placeholder="用户"></Input>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="数据库密码" prop="dbPassword">
                            <Input v-model="dbInfo.dbPassword" type="password" placeholder="密码"></Input>
                        </FormItem>
                    </Col>
                </Row>
                <div class="db-btn">
                    <Button type="success" size="small" @click="test(index)">连接测试</Button>
                    <Button type="warning" size="small" @click="tables(index)">接口配置</Button>
                    <Button size="small" type="error" v-if="index !== 0" @click="deleteDb(index)">删除</Button>
                </div>
            </Form>
        </div>
        <Modal
                v-model="modalShow"
                title="数据库表" width="720" :transfer="false">
            <Table :columns="columns" :data="tableList" height="500" size="small" ref="apiTables"></Table>
            <div slot="footer">
                <Button type="text" @click="modalShow = false">取消</Button>
                <Button type="primary" @click="setApis">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                modalShow: false,
                dbTempName: '',
                app: {
                    appDbList: [{
                        name: '',
                        dbType: 'mysql',
                        dbUrl: '',
                        dbPort: '',
                        dbPassword: '',
                        dbUser: '',
                        isMaster: '1'
                    }],
                    crudTableMap: {}
                },
                dbValidate: {
                    'name': [{
                        required: true, message: '数据库名称不能为空', trigger: 'blur'
                    }],
                    'dbUrl': [{
                        required: true, message: '数据库地址不能为空', trigger: 'blur'
                    }],
                    'dbPort': [{
                        required: true, message: '数据库端口不能为空', trigger: 'blur'
                    }],
                    'dbPassword': [{
                        required: true, message: '数据库密码不能为空', trigger: 'blur'
                    }],
                    'dbUser': [{
                        required: true, message: '数据库用户不能为空', trigger: 'blur'
                    }]
                },
                tableList:[],
                columns:[{
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },{
                    title: '表名',
                    key: 'tableName'
                },{
                    title: '注释',
                    key: 'comments'
                }]
            };
        },
        created() {
        },
        methods: {
            setApis(){
                this.app.crudTableMap[this.dbTempName] = [];
                let arr = this.$refs['apiTables'].getSelection();
                arr.forEach(item => {
                    this.app.crudTableMap[this.dbTempName].push(item.tableName);
                });
                this.modalShow = false;
            },
            tables(index){
                this.$refs['formValidate'][index].validate((valid) => {
                    if (valid) {
                        this.$axios.post('/mdo/api/v1/app/dbTables', this.app.appDbList[index]).then(res => {
                            this.tableList = res.data.map(item => {
                                if (this.app.crudTableMap[this.app.appDbList[index].name] && this.app.crudTableMap[this.app.appDbList[index].name].indexOf(item.tableName) > -1) {
                                    item._checked = true;
                                }
                                return item;
                            });
                            this.dbTempName = this.app.appDbList[index].name;
                            this.modalShow = true;
                            if (!this.app.crudTableMap[this.app.appDbList[index].name]) {
                                this.$set(this.app.crudTableMap, this.app.appDbList[index].name, []);
                            }
                        }).catch(e => {
                            this.$Modal.error({
                                title: '连接失败',
                                content: e.response.data
                            });
                        });
                    }
                });
            },
            dbEdit() {
                this.app.appDbList.push({
                    name: '',
                    dbType: 'mysql',
                    dbUrl: '',
                    dbPort: '',
                    dbPassword: '',
                    dbUser: '',
                    isMaster: '0'
                });
            },
            deleteDb(index) {
                this.$delete(this.app.crudTableMap, this.app.appDbList[index].name);
                this.app.appDbList.splice(index, 1, null);
            },
            test(index, flag) {
                return new Promise((resolve) => {
                    this.$refs['formValidate'][index].validate((valid) => {
                        if (valid) {
                            this.$axios.post('/mdo/api/v1/app/dbCheck', this.app.appDbList[index]).then(res => {
                                if (res.status === 200 && !flag) {
                                    this.$Modal.success({
                                        title: '数据库' + this.app.appDbList[index].name + '连接成功'
                                    });
                                }
                                resolve(this.app.appDbList[index]);
                            }).catch(e =>{
                                this.$Modal.error({
                                    title: '数据库' + this.app.appDbList[index].name + '连接失败',
                                    content: e.response.data
                                });
                            });
                        }
                    });
                });
            },
            async getData(){
                let arr = [];
                for (let i = 0; i < this.app.appDbList.length; i++) {
                    if (this.app.appDbList[i]) {
                        arr.push(this.test(i, true));
                    }
                }
                let result = await Promise.all(arr);
                return {appDbList:result, crudTableMap: this.app.crudTableMap};
            }
        }
    };
</script>

<style lang="less" scoped>
    .db-btn {
        button {
            margin-right: 8px;
        }
        margin-bottom: 18px;
    }
</style>